package com.lucene.index;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.nvm.lucene.NVMAnalyzer;

import com.common.JunitConsole;
import com.lucene.LuceneUtil;

/**
 * @author Smile.Wu
 * @date 2016年1月18日  下午1:46:36
 */
public class IndexWriterTest extends JunitConsole {

	Directory directory = null;
	IndexWriterConfig writerConfig = null;
	IndexWriter indexWriter = null;
	@Before
	public void init() throws IOException {
		directory = FSDirectory.open(new File(LuceneUtil.INDEX_FOLDER));
		writerConfig = new IndexWriterConfig(Version.LUCENE_46, new NVMAnalyzer(false));
		indexWriter = new IndexWriter(directory, writerConfig);
	}
	@After
	public void close() throws IOException {
		if(indexWriter != null) {
			indexWriter.close();
		}
	}
	
	@Test
	public void testWriteIndex() throws IOException {
		List<Position> positions = LuceneUtil.readPosition();
		if(positions != null && positions.size() > 0) {
			console("read {} positions", positions.size());
			for(Position p : positions) {
				Document doc = p.toDocument();
				indexWriter.addDocument(doc);
				console("add doc[{}]", doc);
			}
			indexWriter.commit();
		} else {
			console("can't read positions");
		}
	}
}
